/**
 * 读取流中的数据
 * Created by Tenny on 2018/7/10 16:51.
 */
const zlib = require('zlib');
const getBody = require('raw-body');

/**
 * 读取 request 中的内容 Stream
 * @param req Nodejs request
 */
function contentStream(req) {
  let encoding = (req.headers['content-encoding'] || 'identity').toLowerCase();
  let length = req.headers['content-length'];
  let stream;
  switch (encoding) {
    case 'deflate':
      stream = zlib.createInflate();
      req.pipe(stream);
      break;
    case 'gzip':
      stream = zlib.createGunzip();
      req.pipe(stream);
      break;
    case 'identity':
      stream = req;
      stream.length = length;
      break;
    default: {
      let error = new Error(`unsupported content encoding ${encoding}`);
      error.status = 415;
      throw error;
    }
  }
  return stream;
}

/**
 * 读取输入了中的数据
 * @param req     Nodejs request
 * @param parse   数据解析函数
 * @param options 对应的解析模式的配置
 */
async function read(req, parse, options) {
  let stream = contentStream(req);
  let length = stream.length;
  stream.length = void 0;
  options.length = length;
  let text = await getBody(stream, options);
  return parse(text);
}

module.exports = read;